<template>
  <div class="upload">
    <h2>上传图片</h2>
    <form @submit.prevent="submitForm">
      <div class="select">
        <label for="file">选择图片：</label>
        <input type="file" name="file" id="file" ref="fileInput" /><br /><br />
      </div>
      <div class="select">
        <label for="name">图片名称：</label>
        <input type="text" name="name" id="name" v-model="name" /><br /><br />
      </div>
      <div class="select">
        <label for="orderId">订单号：</label>
        <input
          type="text"
          name="orderId"
          id="orderId"
          v-model="orderId"
        /><br /><br />
      </div>
      <button type="submit">上传</button>
    </form>
    <div v-if="showSuccess" class="alert alert-success">提交成功！</div>
    <div v-if="showError" class="alert alert-danger">提交失败，请重试。</div>
  </div>
</template>

<script>
import axios from "../services/request.js";
// import axios from "axios";

export default {
  data() {
    return {
      name: "",
      orderId: "",
      showSuccess: false,
      showError: false,
    };
  },
  methods: {
    submitForm() {
      const formData = new FormData();
      formData.append("file", this.$refs.fileInput.files[0]);
      formData.append("name", this.name);
      formData.append("orderId", this.orderId);

      axios
        .post("/upload/upload", formData)
        .then(() => {
          this.showSuccess = true;
          setTimeout(() => {
            this.showSuccess = false;
          }, 2000);
        })
        .catch(() => {
          this.showError = true;
          setTimeout(() => {
            this.showError = false;
          }, 2000);
        });
    },
  },
};
</script>

<style lang="less" scoped>
.upload {
  height: 100vh;
  background-color: rgb(242, 242, 242);
  form {
    background-color: #fff;
    margin: 20px;
    padding: 20px;
    border: 1px solid #cbcbcb;
    border-radius: 10px;
    .select {
      display: flex;
      flex-direction: column;
      label {
        font-weight: 700;
      }
      input {
        margin: 10px 0;
        padding: 10px;
        border: 1px solid #cbcbcb;
        border-radius: 5px;
      }
    }
    button {
      background-color: rgb(76, 175, 80);
      padding: 10px 20px;
      border: none;
      font-size: 14px;
      border-radius: 5px;
    }
  }
}
.alert {
  position: fixed;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  padding: 10px 20px;
  border-radius: 5px;
  color: #fff;
  font-size: 16px;
  text-align: center;
  z-index: 9999;
}
.alert-success {
  background-color: #4caf50;
}
.alert-danger {
  background-color: #f44336;
}
</style>
